package top.yunjianwang.event;

import org.bukkit.Server;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.plugin.java.JavaPlugin;

import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;


public class MyEventHandler implements Listener {
    private Set<String> WhiteList = new HashSet<>();

    public MyEventHandler(JavaPlugin thisPlugin){
        YamlConfiguration white_list = new YamlConfiguration();
        try {
            white_list.load(new File(thisPlugin.getDataFolder(), "whitelist.yml"));
        } catch (IOException | InvalidConfigurationException e) {
            e.printStackTrace();
        }

        List<?> whitelist = white_list.getList("whitelist");
        if (whitelist instanceof Set) {
            this.WhiteList = new HashSet<>((Collection<String>) whitelist);
        }
    }

    /**
     * on Player join server
     *
     * @param event PlayerJoinEvent
     */
    @EventHandler
    public void PlayerJoin(PlayerJoinEvent event) {
        if (!is_in_whitelist(event)) {
            event.getPlayer().kickPlayer("You aren't in white list. Please call the server owner.");
        }
    }


    public Set<String> getWhiteList() {
        if (this.WhiteList != null) {
            return WhiteList;
        }
        return new HashSet<>();
    }

    private boolean is_in_whitelist(PlayerJoinEvent event) {
        Player player = event.getPlayer();
        String player_name = player.getName();
        return WhiteList.contains(player_name);
    }

}
